package com.example.wn.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.example.wn.common.exception.WeiNongException;
import com.example.wn.mapper.SysRoleUserMapper;
import com.example.wn.mapper.SysUserMapper;
import com.example.wn.model.dto.system.AssginRoleDto;
import com.example.wn.model.dto.system.LoginDto;
import com.example.wn.model.dto.system.SysUserDto;
import com.example.wn.model.entity.system.SysUser;
import com.example.wn.model.vo.common.ResultCodeEnum;
import com.example.wn.model.vo.system.LoginVo;
import com.example.wn.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 判断验证码
        String codeKey = loginDto.getCodeKey();
        String captcha = loginDto.getCaptcha();
        String trueCaptcha = redisTemplate.opsForValue().get("user:login:validcode:" + codeKey);
        // 判断验证码是否正确
        if (StrUtil.isEmpty(captcha) || !StrUtil.equalsIgnoreCase(captcha, trueCaptcha)) {
            throw new WeiNongException(ResultCodeEnum.VALIDATECODE_ERROR);
        }

        // 验证通过删除redis中的验证码
        redisTemplate.delete("user:login:validcode:" + codeKey) ;

        //1 根据用户名查找用户
        SysUser sysUser = sysUserMapper.selectByUserName(loginDto.getUserName());

        // 用户不存在
        if (sysUser == null){
            throw new WeiNongException(ResultCodeEnum.LOGIN_ERROR);
        }

        //2 比较密码是否匹配
        String dtoPassword = loginDto.getPassword();
        String userPassword = sysUser.getPassword();
        String inputPassword = DigestUtils.md5DigestAsHex(dtoPassword.getBytes(StandardCharsets.UTF_8));

        // 密码错误
        if (!userPassword.equals(inputPassword)){
            throw  new RuntimeException("密码不正确！");
        }

        //3 生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //4 将用户信息存入redis
        redisTemplate.opsForValue()
                .set("login:" + token, JSON.toJSONString(sysUser), 30, TimeUnit.MINUTES);

        //5 返回token给前端
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);

        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        
        // 从Redis中查询是否存在token
        String user = redisTemplate.opsForValue().get("login:" + token);
        if (StrUtil.isEmpty(user)){
            throw new WeiNongException(ResultCodeEnum.LOGIN_AUTH);
        }

        SysUser sysUser = JSON.parseObject(user, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("login:" + token);
    }

    @Override
    public PageInfo<SysUser> findByPage(SysUserDto sysUserDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum , pageSize);
        List<SysUser> sysUserList = sysUserMapper.findByPage(sysUserDto) ;
        PageInfo pageInfo = new PageInfo(sysUserList) ;
        return pageInfo;
    }

    @Override
    public void saveSysUser(SysUser sysUser) {

        // 根据输入的用户名查询用户
        SysUser dbSysUser = sysUserMapper.selectByUserName(sysUser.getUserName()) ;
        if(dbSysUser != null) {
            throw new WeiNongException(ResultCodeEnum.USER_NAME_IS_EXISTS) ;
        }

        // 对密码进行加密
        String password = sysUser.getPassword();
        String digestPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        sysUser.setPassword(digestPassword);
        sysUser.setStatus(0);
        sysUserMapper.saveSysUser(sysUser) ;
    }

    @Override
    public void updateSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser) ;
    }

    public void deleteById(Long userId) {
        sysUserMapper.deleteById(userId) ;
    }

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;

    @Transactional
    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {

        // 删除之前的所有的用户所对应的角色数据
        sysRoleUserMapper.deleteByUserId(assginRoleDto.getUserId()) ;

        // 分配新的角色数据
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        roleIdList.forEach(roleId->{
            sysRoleUserMapper.doAssign(assginRoleDto.getUserId(),roleId);
        });
    }
}
